package com.hw.job_2;

/**
 * 编程获取两个指定字符串中的最大相同子串。
 *  如： s1="asdafghjka", s2="aaasdfg" 他们的最大子串为"asd"
 *  提示： 将短的那个串进行长度依次递减的子串与较长的串比较。
 */
public class job_2 {

    public static void main(String[] args) {

        String s1 = "asdafghjka";
        String s2 = "aaasdfg";

        s1 = "123abc123abcde0000";
        s2 = "123abcde";

        s1 = "asdafghjkaasdfg111asdf";
        s2 = "aaasdfg";

        // 确定哪个字符串比较长
        String shortStr;
        String longStr;
        if (s1.length() >= s2.length()) {
            longStr = s1;
            shortStr = s2;
        } else {
            longStr = s2;
            shortStr = s1;
        }

        // 思路：
        // 外层循环，遍历短字符串，长度依次递减
        // 内层循环，遍历长字符串，依次和短字符串的开头进行比较，直到和短字符串不一致时，记录子串
        // 每次循环遍历到的子串，都和上一次子串对比，若大于或等于，则替换
        // lastSubComStr，记录上一次的子串
        StringBuilder lastSubComStr = new StringBuilder();
        StringBuilder subComStr = new StringBuilder();
        for (int i = 0; i < shortStr.length(); i++) {
            // 记录此次循环的子串
            int shortIndex = i;
            // 记录长串开始的位置
            int longIndex = 0;
            for (int j = longIndex; j < longStr.length(); j++) {
                char shortChar = shortStr.charAt(shortIndex);
                char longChar = longStr.charAt(j);
//                System.out.println("shortIndex = " + shortIndex + ", j = " + j);
//                System.out.println("shortChar = " + shortChar + ", longChar = " + longChar);
                if (shortChar == longChar) {
                    subComStr.append(shortChar);
//                    System.out.println("shortChar = " + shortChar + ", subComStr = " + subComStr);
                    shortIndex++;
                    // 当索引超出时，退出内循环
                    if (shortIndex >= shortStr.length()) {
                        // 比较当前循环子串和上一次子串，进行替换
                        if (subComStr.length() >= lastSubComStr.length()) {
                            lastSubComStr = subComStr;
                        }
                        subComStr = new StringBuilder();
                        longIndex++;
                        j = longIndex;
                        break;
                    }
                } else {
                    // 比较当前循环子串和上一次子串，进行替换
                    if (subComStr.length() >= lastSubComStr.length()) {
                        lastSubComStr = subComStr;
                    }
                    subComStr = new StringBuilder();
                    // 重置短串的索引
                    shortIndex = i;
                    longIndex++;
                    j = longIndex;
                }
            }
        }

        System.out.println(s1 + " 和 " + s2 + " 的最大子串是 " + lastSubComStr);
    }
}
